package com.chinamobile.ln.ictenterprises.utils;

import java.util.Stack;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

/**
 * Activity栈管理
 * @author FuLei
 *
 */
public class ActivityStackManager {

    
    private static Stack<Activity> activityStack;
    private static ActivityStackManager instance = null;
    
    /**
     * 单例
     * @return
     */
    public static ActivityStackManager getManager(){
        if(instance == null){
            instance = new ActivityStackManager();
        }
        return instance;
    }
    
    /**
     * 添加Activity到Stack
     * @param activity
     */
    public void addActivity(Activity activity){
        if(activityStack == null){
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }
    
    /**
     * 获取当前Activity(堆栈中最后一个压入的)
     * @return
     */
    public Activity currentActivity(){
        Activity activity = activityStack.lastElement();
        return activity;
    }
    
    /**
     * 结束当前Activity(堆栈中最后一个压入的)
     */
    public void finishActivity(){
        Activity activity = activityStack.lastElement();
        if(activity != null){
            activity.finish();
            activity = null;
        }
    }
    
    /**
     * 判断传入的activiy是否存在
     * @param cls
     * @return
     */
    public boolean hasActivtiy(Class<?> cls){
        boolean flag = false;
        for (Activity activity : activityStack) {
            if(activity.getClass().getName().equals(cls.getName())){
                flag = true;
                break;
            }
        }
        return flag;
    }
    
    /**
     * 结束指定的Activity
     * @param cls
     */
    public void finishActivity(Class<?> cls){
        for (Activity activity : activityStack) {
            if(activity.getClass().equals(cls)){
                activity.finish();
                activity = null;
            }
        }
    }
    
    /**
     * 结束所有Activity
     */
    public void finishAllActivity(){
        for (Activity activity : activityStack) {
            if(activity != null){
                activity.finish();
                activity = null;
            }
        }
        activityStack.clear();
    }
    
    /**
     * 退出应用程序
     * @param context
     */
    @SuppressWarnings("deprecation")
    public void exitApp(Context context){
        try {
            finishAllActivity();
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.restartPackage(context.getPackageName());
            System.exit(0);
        }
        catch (Exception e) {
        }
    }
}
